﻿namespace Borg.Framework
{
    public class RegisterComboBox : ComboBox, IAttachable
    {
        public RegisterComboBox()
        {
            Enabled = false;
        }

        public void Attach(SlotInfo slot)
        {
            Slot = slot;
            
            Slot.Registered += Registered;
            Slot.Deregistered += Deregistered;
            
            Items.Clear();

            foreach (var pti in Slot.RegisteredPlugTypeInfos)
                Items.Add(pti, pti.ExtensionTypeInfo);

            Enabled = true;
        }

        public void Deregistered(object sender, RegisterEventArgs args)
        {
            Items.Remove(args.PlugTypeInfo);
        }

        public void Detach()
        {
            Enabled = false;

            Slot.Registered -= Registered;
            Slot.Deregistered -= Deregistered;

            Items.Clear();
            Slot = null;
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (Slot != null)
                Detach();
        }

        public void Registered(object sender, RegisterEventArgs args)
        {
            Items.Add(args.PlugTypeInfo, args.PlugTypeInfo.ExtensionTypeInfo);
        }

        private SlotInfo Slot { get; set; }
    }
}

